﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BaHuan.BusinessLayer;
using BaHuan.Common;
using BaHuan.Entities;
using BaHuan.Utils;

namespace BaHuan
{
    public partial class FrmPhieuChiTien : Form
    {
        private ChiNhanhCongTyMgt chinhanhctyMgt = new ChiNhanhCongTyMgt();
        private KhachHangManagement khachhangMgt = new KhachHangManagement();
        private NhaCungCapManagement nhacungcapMgt = new NhaCungCapManagement();
        private NhanVienMgt nhanvienMgt = new NhanVienMgt();
        private PhieuChiTienManagement phieuchitienMgt = new PhieuChiTienManagement();
        private BangKeNhapHangMgt bangkeMgt = new BangKeNhapHangMgt();
        private ButToanMgt buttoanMgt = new ButToanMgt();
        private MucChiMgt mucchiMgt = new MucChiMgt();
        private BangMaPhieuMgt bangmaphieuMgt = new BangMaPhieuMgt();

        private int idLoaiPhieu = 12;
        private bool IsEdited;
        private PhieuNhapKho mphieunhapkho = null;
        private MuaHang mMuaHang = null;
        private PhieuChiTien mPhieuChiTien = null;

        private DateTime dtOld = new DateTime();
        private string prefixOld = "";

        private NhanVien nhanvien;
        public NhanVien NhanVien
        {
            set { this.nhanvien = value; }
            get { return this.nhanvien; }
        }

        public FrmPhieuChiTien(PhieuChiTien phieuchitien, NhanVien nv)
        {
            InitializeComponent();

            ResultObj result = new ResultObj();

            gbThongTinChiTien.Enabled = false;
            btnLuu.Enabled = false;
            btnSua.Enabled = true;
            btnXoa.Enabled = true;
            btnDinhKhoan.Enabled = true;
            btnIn.Enabled = true;

            this.mPhieuChiTien = phieuchitien;
            this.NhanVien = nv;
            BindingToCbo();

            result = chinhanhctyMgt.GetAllChiNhanhCongTy();
            ChiNhanhCongTy chinhanhcongty = (from cn in (List<ChiNhanhCongTy>)result.Result
                                                 where cn.Id == this.mPhieuChiTien.IdChiNhanhCongTy
                                                 select cn).FirstOrDefault();

            dtOld = this.mPhieuChiTien.NgayThang;
            dtpNgayLap.Value = this.mPhieuChiTien.NgayThang;
            dtpNgayThucChi.Value = this.mPhieuChiTien.NgayThucChi.Value;

            prefixOld = this.mPhieuChiTien.Prefix;
            cboPrefix.Text = this.mPhieuChiTien.Prefix;
            txtMaPhieuChi.Text = this.mPhieuChiTien.OrderNumber;
            
            cboDonViChi.Text = chinhanhcongty.TenChiNhanh;
            txtNguoiNhan.Text = this.mPhieuChiTien.NguoiNhanTien;
            cboDoiTuong.Text = this.mPhieuChiTien.DoiTuong;
            txtLyDo.Text = this.mPhieuChiTien.LyDo;
            txtSoTien.Text = this.mPhieuChiTien.SoTien.ToString();
            txtNguoiLap.Text = this.mPhieuChiTien.NguoiLap;
            txtKemTheo.Text = this.mPhieuChiTien.ChungTuKemTheo;
            lblId.Text = this.mPhieuChiTien.Id.ToString();
        }

        public FrmPhieuChiTien(NhanVien nhanvien)
        {
            InitializeComponent();

            this.nhanvien = nhanvien;
            txtNguoiLap.Text = nhanvien.HoTen;

            cboLoaiDoiTuong.SelectedIndex = 1;
            BindingToCbo();

            btnLuu.Enabled = true;
            btnSua.Enabled = false;
            btnXoa.Enabled = false;
            btnDinhKhoan.Enabled = false;
            btnIn.Enabled = false;
        }

        public FrmPhieuChiTien(PhieuNhapKho phieunhapkho, long sotienconthieu, long sotiendatra, NhanVien nv, bool IsThem)
        {
            InitializeComponent();

            mphieunhapkho = phieunhapkho;
            this.nhanvien = nv;
            btnThem.Enabled = IsThem;
            txtNguoiLap.Text = nv.HoTen;
            cboLoaiDoiTuong.SelectedIndex = 1;
            BindingToCbo();          

            txtSoTien.Text = sotienconthieu.ToString();
            txtSoTienDaTra.Text = sotiendatra.ToString();
            cboDonViChi.SelectedValue = phieunhapkho.IdChiNhanhCTy;
            txtKemTheo.Text = phieunhapkho.MaSo;

            List<BangKeNhapHang> lstBangKeNhapHang = (from bk in GetAllBangKeNhapHang()
                                                      where bk.Id == phieunhapkho.IdBangKe &&
                                                      bk.IsDelete==0
                                                      select bk).ToList();

            if (lstBangKeNhapHang.Count > 0)
                cboDoiTuong.SelectedIndex = cboDoiTuong.FindString(lstBangKeNhapHang[0].NhaCungCap);

            btnLuu.Enabled = true;
            btnSua.Enabled = false;
            btnXoa.Enabled = false;
            btnDinhKhoan.Enabled = false;
            btnIn.Enabled = false;
        }

        public FrmPhieuChiTien(MuaHang muahang, long sotienconthieu, long sotiendatra, NhanVien nv, bool IsThem)
        {
            InitializeComponent();

            mMuaHang = muahang;
            this.nhanvien = nv;

            btnThem.Enabled = IsThem;
            txtNguoiLap.Text = nv.HoTen;
            cboLoaiDoiTuong.SelectedIndex = 1;
            BindingToCbo();
            
            txtSoTien.Text = sotienconthieu.ToString();
            txtSoTienDaTra.Text = sotiendatra.ToString();
            cboDonViChi.SelectedValue = muahang.IdChiNhanhCongTy;
            txtKemTheo.Text = muahang.MaSo;
            cboDoiTuong.SelectedIndex = cboDoiTuong.FindString(muahang.NhaCungCap);

            btnLuu.Enabled = true;
            btnSua.Enabled = false;
            btnXoa.Enabled = false;
            btnDinhKhoan.Enabled = false;
            btnIn.Enabled = false;
        }

        public void BindingToCbo()
        {
            cboDonViChi.DataSource = GetAllChiNhanhCongTy();
            cboDonViChi.DisplayMember = "TenChiNhanh";
            cboDonViChi.ValueMember = "Id";

            cboMucChi.DataSource = GetAllMucChi();
            cboMucChi.DisplayMember = "Ten";
            cboMucChi.ValueMember = "Id";

            cboPrefix.DataSource = GetAllBangMaPhieu(idLoaiPhieu);
            cboPrefix.DisplayMember = "MaSo";
            cboPrefix.ValueMember = "Id";
        }

        public void RefreshControl()
        {
            txtNguoiNhan.Text = "";
            txtSubMucChi.Text = "";
            txtLyDo.Text = "";
            txtKemTheo.Text = "";
            txtSoTien.Text = "";
            cboPrefix.Text = "";

            cboDonViChi.SelectedIndex = -1;
            cboLoaiDoiTuong.SelectedIndex = -1;
            cboDoiTuong.SelectedIndex = -1;

            lblId.Text = "";
            dtpNgayLap.Value = DateTime.Now;
            dtpNgayThucChi.Value = DateTime.Now;
        }

        private void cboLoaiDoiTuong_SelectedValueChanged(object sender, EventArgs e)
        {
            if (cboLoaiDoiTuong.SelectedIndex > -1)
            {
                int loaiDoiTuong = cboLoaiDoiTuong.SelectedIndex;
                switch (loaiDoiTuong)
                {
                    case 0:
                        cboDoiTuong.DataSource = null;
                        cboDoiTuong.DataSource = GetAllKhachHang();
                        cboDoiTuong.DisplayMember = "Ten";
                        cboDoiTuong.ValueMember = "MaSoKhachHang";
                        break;
                    case 1:
                        cboDoiTuong.DataSource = null;
                        cboDoiTuong.DataSource = GetAllNhaCungCap();
                        cboDoiTuong.DisplayMember = "TenNhaCungCap";
                        cboDoiTuong.ValueMember = "Id";
                        break;
                    case 2:
                        cboDoiTuong.DataSource = null;
                        cboDoiTuong.DataSource = GetAllNhanVien();
                        cboDoiTuong.DisplayMember = "HoTen";
                        cboDoiTuong.ValueMember = "Id";
                        break;
                    case 3:
                        cboDoiTuong.DataSource = null;
                        cboDoiTuong.DataSource = GetAllChiNhanhCongTy();
                        cboDoiTuong.DisplayMember = "TenChiNhanh";
                        cboDoiTuong.ValueMember = "Id";
                        break;
                }
            }
        }

        private void cboDoiTuong_SelectedValueChanged(object sender, EventArgs e)
        {
            int loaiDoiTuong = cboLoaiDoiTuong.SelectedIndex;
            if (cboDoiTuong.SelectedItem != null)
            {
                switch (loaiDoiTuong)
                {
                    case 0:
                        lblDiaChi.Text = ((KhachHang)cboDoiTuong.SelectedItem).DiaChi;
                        break;
                    case 1:
                        lblDiaChi.Text = ((NhaCungCap)cboDoiTuong.SelectedItem).DiaChi;
                        break;
                    case 2:
                        lblDiaChi.Text = "";
                        break;
                    case 3:
                        lblDiaChi.Text = ((ChiNhanhCongTy)cboDoiTuong.SelectedItem).DiaChiChiNhanh;
                        break;
                }
            }
        }

        private void btnDinhKhoan_Click(object sender, EventArgs e)
        {
            FrmDinhKhoanPhieuChiTien frmDinhKhoanPhieuChiTien = new FrmDinhKhoanPhieuChiTien();
            this.mPhieuChiTien.Id = Convert.ToInt32(lblId.Text);
            frmDinhKhoanPhieuChiTien.PhieuChiTien = this.mPhieuChiTien;
            frmDinhKhoanPhieuChiTien.Show();
        }

        private void btnThoat_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnThem_Click(object sender, EventArgs e)
        {
            btnLuu.Enabled = true;
            btnSua.Enabled = false;
            btnXoa.Enabled = false;
            btnIn.Enabled = false;
            btnDinhKhoan.Enabled = false;

            prefixOld = "";
            dtOld = new DateTime();

            RefreshControl();
            txtNguoiLap.Text = this.nhanvien.HoTen;

            gbThongTinChiTien.Enabled = true;
            IsEdited = false;
        }

        private void btnLuu_Click(object sender, EventArgs e)
        {
            if (txtMaPhieuChi.Text == "")
            {
                MessageBox.Show("Vui lòng chọn mã phiếu");
                return;
            }

            if (txtSoTien.Text.Replace(".", "") == "" || cboDonViChi.Text == "")
            {
                MessageBox.Show("Vui lòng nhập đầy đủ thông tin cần thiết","Thông báo");
                return;
            }
            else
            {
                ResultObj resultObj = new ResultObj();

                mPhieuChiTien = new PhieuChiTien();
                mPhieuChiTien.Prefix = cboPrefix.Text;
                mPhieuChiTien.OrderNumber = txtMaPhieuChi.Text;
                mPhieuChiTien.MaSo = cboPrefix.Text + "/" + dtpNgayLap.Value.ToString("MM") + dtpNgayLap.Value.ToString("yy") + "/" + txtMaPhieuChi.Text;
                mPhieuChiTien.History = "";
                mPhieuChiTien.NgayThang = dtpNgayLap.Value;
                mPhieuChiTien.NgayThucChi = dtpNgayThucChi.Value;
                mPhieuChiTien.NguoiNhanTien = txtNguoiNhan.Text;
                mPhieuChiTien.LyDo = txtLyDo.Text;
                mPhieuChiTien.NguoiLap = txtNguoiLap.Text;

                if (cboDonViChi.SelectedItem == null)
                    return;
                mPhieuChiTien.IdChiNhanhCongTy = ((ChiNhanhCongTy)cboDonViChi.SelectedItem).Id;

                if (cboDoiTuong.Text == "")
                {
                    MessageBox.Show("Vui lòng chọn đối tượng","Thông báo");
                    return;
                }

                mPhieuChiTien.DoiTuong = cboDoiTuong.Text;

                if (string.IsNullOrEmpty(txtSoTien.Text))
                {
                    MessageBox.Show("Vui lòng nhập số tiền","Thông báo");
                    return;
                }
                mPhieuChiTien.SoTien = Convert.ToInt64(txtSoTien.Text.Replace(".", ""));

                mPhieuChiTien.ChungTuKemTheo = txtKemTheo.Text;                

                if (mphieunhapkho != null)
                    mPhieuChiTien.IdNhapHang = mphieunhapkho.Id;
                else
                    mPhieuChiTien.IdNhapHang = 0;

                if (mMuaHang != null)
                    mPhieuChiTien.IdMuaHang = mMuaHang.Id;
                else
                    mPhieuChiTien.IdMuaHang = 0;

                //save
                if (!IsEdited)
                {
                    mPhieuChiTien.IsDelete = 0;
                    resultObj = phieuchitienMgt.SaveNewPhieuChiTien(mPhieuChiTien);
                    lblId.Text = resultObj.ReturnCode.ToString();
                }
                //update
                else
                {
                    mPhieuChiTien.Id = Convert.ToInt32(lblId.Text);
                    mPhieuChiTien.IsDelete = 0;
                    resultObj = phieuchitienMgt.UpdatePhieuChiTien(mPhieuChiTien);
                }

                if (resultObj.ReturnCode > 0)
                {
                    EditOrRemoveDinhKhoan(mPhieuChiTien.MaSo);
                    MessageBox.Show("Lưu thành công. Vui lòng cập nhật lại các bút toán.", "Thông báo");

                    btnDinhKhoan.Enabled = true;
                    btnIn.Enabled = true;
                    btnSua.Enabled = true;
                    btnXoa.Enabled = true;
                    btnThem.Enabled = true;
                    btnLuu.Enabled = false;
                    gbThongTinChiTien.Enabled = false;
                }
                    
                else if (resultObj.ReturnCode == Definitions.DUPLICATED_VALUE)
                    MessageBox.Show("Dữ liệu bị trùng", "Thông báo");
                else
                    MessageBox.Show("Lưu không thành công","Thông báo");
            }
        }

        private void btnSua_Click(object sender, EventArgs e)
        {
            gbThongTinChiTien.Enabled = true;
            btnLuu.Enabled = true;
            IsEdited = true;

            btnXoa.Enabled = false;
            btnDinhKhoan.Enabled = false;
            btnIn.Enabled = false;
            btnSua.Enabled = false;
        }

        private void btnIn_Click(object sender, EventArgs e)
        {
            string sLoaiPhieuChi = "";
            if (mphieunhapkho != null || mMuaHang != null)
                sLoaiPhieuChi = "TIỀN HÀNG";

            string tienchu = CNum2Char.So2Chu((long)Convert.ToDouble(txtSoTien.Text.Replace(".", "")));
            string diachi = lblDiaChi.Text;

            FrmXemReport frm = new FrmXemReport(mPhieuChiTien, sLoaiPhieuChi, tienchu, diachi);
            this.Hide();
            frm.ShowDialog();
            this.Show();
        }

        private void btnXoa_Click(object sender, EventArgs e)
        {
            btnLuu.Enabled = false;
            btnSua.Enabled = false;
            btnXoa.Enabled = false;
            btnDinhKhoan.Enabled = false;
            btnIn.Enabled = false;

            ResultObj result = new ResultObj();

            mPhieuChiTien.Id = Convert.ToInt32(lblId.Text);
            mPhieuChiTien.IsDelete = 1;

            result = phieuchitienMgt.UpdatePhieuChiTien(mPhieuChiTien);
            EditOrRemoveDinhKhoan(mPhieuChiTien.MaSo);

            if (result.ReturnCode > 0)
            {
                MessageBox.Show("Đã xoá thành công.", "Thông báo");
                this.Close();
            }

            else if (result.ReturnCode == Definitions.DUPLICATED_VALUE)
                MessageBox.Show("Dữ liệu bị trùng !", "Thông báo");
            else
                MessageBox.Show("Xoá Thất bại !","Thông báo");
                     
        }

        private void txtSoTien_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!Char.IsDigit(e.KeyChar) && !Char.IsControl(e.KeyChar))
            {
                MessageBox.Show("Vui lòng nhập số !");
                e.Handled = true;
            }
        }

        private void txtSoTien_TextChanged(object sender, EventArgs e)
        {
            if (txtSoTien.Text != "")
            {
                txtSoTien.SelectionStart = txtSoTien.Text.Length + 1;
                string num = txtSoTien.Text.Replace(".", "");
                txtSoTien.Text = (Convert.ToInt64(num).ToString("N0")).Replace(",", ".");
            }
        }

        private void cboPrefix_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (prefixOld != ((BangMaPhieu)cboPrefix.SelectedItem).MaSo)
                txtMaPhieuChi.Text = cboPrefix.Text == "" ? "" : KiemTraMaSo.CheckCode(((BangMaPhieu)cboPrefix.SelectedItem).MaSo, idLoaiPhieu, dtpNgayLap.Value);
        }

        private void cboDoiTuong_Leave(object sender, EventArgs e)
        {
            if (cboLoaiDoiTuong.SelectedIndex == 0)
            {
                foreach (KhachHang c in cboDoiTuong.Items)
                {
                    if (c.Ten.ToLower().Contains(cboDoiTuong.Text) && cboDoiTuong.Text != "")
                    {
                        cboDoiTuong.SelectedValue = c.Id;
                        break;
                    }
                }
            }
            else if (cboLoaiDoiTuong.SelectedIndex == 1)
            {
                foreach (NhaCungCap p in cboDoiTuong.Items)
                {
                    if (p.TenNhaCungCap.ToLower().Contains(cboDoiTuong.Text) && cboDoiTuong.Text != "")
                    {
                        cboDoiTuong.SelectedValue = p.Id;
                        break;
                    }
                }
            }
            else if (cboLoaiDoiTuong.SelectedIndex == 2)
            {
                foreach (NhanVien emp in cboDoiTuong.Items)
                {
                    if (emp.HoTen.ToLower().Contains(cboDoiTuong.Text) && cboDoiTuong.Text != "")
                    {
                        cboDoiTuong.SelectedValue = emp.Id;
                        break;
                    }
                }
            }
            else if (cboLoaiDoiTuong.SelectedIndex == 3)
            {
                foreach (ChiNhanhCongTy b in cboDoiTuong.Items)
                {
                    if (b.TenChiNhanh.ToLower().Contains(cboDoiTuong.Text)&& cboDoiTuong.Text!="")
                    {
                        cboDoiTuong.SelectedValue = b.Id;
                        break;
                    }
                }
            }

            if (cboDoiTuong.SelectedValue == null)
            {
                cboDoiTuong.Text = "";
            }
        }

        private void cboDonViChi_Leave(object sender, EventArgs e)
        {
            foreach (ChiNhanhCongTy b in cboDonViChi.Items)
            {
                if (b.TenChiNhanh.ToLower().Contains(cboDonViChi.Text) && cboDonViChi.Text!="")
                {
                    cboDonViChi.SelectedValue = b.Id;
                    break;
                }
            }

            if (cboDonViChi.SelectedValue == null)
            {
                cboDonViChi.Text = "";
            }
        }

        private void dtpNgayLap_ValueChanged(object sender, EventArgs e)
        {
            if (dtOld != dtpNgayLap.Value)
                txtMaPhieuChi.Text = cboPrefix.Text == "" ? "" : KiemTraMaSo.CheckCode(((BangMaPhieu)cboPrefix.SelectedItem).MaSo, idLoaiPhieu, dtpNgayLap.Value);
        }

        private void txtMaPhieuChi_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!Char.IsDigit(e.KeyChar) && !Char.IsControl(e.KeyChar))
            {
                e.Handled = true;
            }
        }

        private void txtMaPhieuChi_Leave(object sender, EventArgs e)
        {
            bool isDup = KiemTraMaSo.CheckOrderNumber(((BangMaPhieu)cboPrefix.SelectedItem).MaSo, txtMaPhieuChi.Text, idLoaiPhieu, dtpNgayLap.Value);
            if (isDup)
            {
                MessageBox.Show("Mã phiếu bị trùng");
                txtMaPhieuChi.Focus();
            }
        }

        public void EditOrRemoveDinhKhoan(string MaSo)
        {
            ResultObj resultObj = new ResultObj();

            List<ButToan> lst = (from p in GetAllButToan()
                                 where p.SoChungTu == MaSo
                                 select p).ToList();

            if (lst.Count > 0)
            {
                foreach (ButToan b in lst)
                {
                    b.IsEdited = 1;
                    resultObj = buttoanMgt.UpdateButToan(b);
                }
            }
        }

        public List<ChiNhanhCongTy> GetAllChiNhanhCongTy()
        {
            ResultObj resultObj = new ResultObj();
            resultObj = chinhanhctyMgt.GetAllChiNhanhCongTy();
            List<ChiNhanhCongTy> listChiNhanhCongTy = (from cn in(List<ChiNhanhCongTy>)resultObj.Result
                                                           where cn.IsDelete==0 
                                                       select cn).ToList();
            return listChiNhanhCongTy;
        }

        public List<KhachHang> GetAllKhachHang()
        {
            ResultObj resultObj = new ResultObj();
            resultObj = khachhangMgt.GetAllKhachHang();
            List<KhachHang> listKhachHang = ((List<KhachHang>)resultObj.Result);
            return listKhachHang;
        }

        public List<NhaCungCap> GetAllNhaCungCap()
        {
            ResultObj resultObj = new ResultObj();
            resultObj = nhacungcapMgt.GetAllNhaCungCap();
            List<NhaCungCap> listNhaCungCap = (from ncc in(List<NhaCungCap>)resultObj.Result
                                                   where ncc.IsDelete==0
                                                   select ncc).ToList();
            return listNhaCungCap;
        }

        public List<NhanVien> GetAllNhanVien()
        {
            ResultObj resultObj = new ResultObj();
            resultObj = nhanvienMgt.GetAllNhanVien();
            List<NhanVien> listNhanVien = (from nv in(List<NhanVien>)resultObj.Result
                                               where nv.IsDelete==0
                                               select nv).ToList();
            return listNhanVien;
        }

        public List<ButToan> GetAllButToan()
        {
            ResultObj resultObj = new ResultObj();

            resultObj = buttoanMgt.GetAllButToan();
            List<ButToan> listButToan = (List<ButToan>)resultObj.Result;

            return listButToan;
        }

        public List<PhieuChiTien> GetAllPhieuChiTien()
        {
            ResultObj resultObj = new ResultObj();
            resultObj = phieuchitienMgt.GetAllPhieuChiTien();
            List<PhieuChiTien> listPhieuChiTien = (from pc in(List<PhieuChiTien>)resultObj.Result
                                                       where pc.IsDelete==0
                                                       select pc).ToList();
            return listPhieuChiTien;
        }

        public List<BangKeNhapHang> GetAllBangKeNhapHang()
        {
            ResultObj resultObj = new ResultObj();

            resultObj = bangkeMgt.GetAllBangKeNhapHang();
            List<BangKeNhapHang> listBangKeNhapHang = (from bk in(List<BangKeNhapHang>)resultObj.Result
                                                           where bk.IsDelete==0
                                                           select bk).ToList();

            return listBangKeNhapHang;
        }

        public List<MucChi> GetAllMucChi()
        {
            ResultObj resultObj = new ResultObj();

            resultObj = mucchiMgt.GetAllMucChi();
            List<MucChi> listMucChi = (List<MucChi>)resultObj.Result;

            return listMucChi;
        }

        public List<BangMaPhieu> GetAllBangMaPhieu(int id)
        {
            ResultObj resultObj = new ResultObj();

            resultObj = bangmaphieuMgt.GetAllBangMaPhieuByIDLoaiPhieu(id);
            List<BangMaPhieu> listBangMaPhieu = (List<BangMaPhieu>)resultObj.Result;

            return listBangMaPhieu;
        }
    }
}
